package com.pinc.wacow;

import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;

import com.pinc.wacow.R;

public class Test_Result extends WidgetActivity {
	private DBClass dbHelper;
	private Summary_Adapter mAdapter;
	private ListView lv;
	private Question_Packet mQP;
	private float mScore;
	private TextView tv_score;
	private TextView tv_qstnNo;
	private TextView tv_wrongNo;
	private ProgressDialog progressDialog;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.test_result);

		dbHelper = new DBClass(this);
		mQP = (Question_Packet) getIntent().getSerializableExtra("packet");
		mAdapter = new Summary_Adapter(this);
		mAdapter.setMode(Summary_Adapter.MODE_ANSWER);

		initWidget();

		for ( int i=0; i<mQP.mQstn_total; i++)
		{
			Summary_Class sc = new Summary_Class(
					mQP.mArr_Qid[i],
					mQP.mQuestion[i],
					mQP.mArr_ansPaper[i],
					mQP.mArr_answer[i]
			);
			mAdapter.add(sc);
		}

		lv.setAdapter(mAdapter);
		lv.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
				Intent intent = new Intent(Test_Result.this, Test_Correct.class);
				intent.putExtra("packet", mQP);
				intent.putExtra("number", position);
				startActivity(intent);
			}
		});

		showScore();
	}

	@Override
	protected void initWidget() {
		super.initWidget();

		lv = (ListView) this.findViewById(R.id.listView1);

		/* set upbar */
		tv_title.setText(getResources().getString(R.string.str_quiz_result));

		b_next.setVisibility(View.VISIBLE);
		b_next.setText(getResources().getString(R.string.str_finish));
		b_next.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				new finishTask().execute(Test_Result.this);
			}
		});

		b_prev.setVisibility(View.VISIBLE);
		b_prev.setText(getResources().getString(R.string.str_save));
		b_prev.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				showDialog(ID_SAVE);
			}
		});

		/* set widget */
		Widget_Window ww = (Widget_Window)this.findViewById(R.id.widgetWindow1);
		ww.init(getResources().getString(R.string.str_quiz_result), new String[]{getResources().getString(R.string.str_quiz_question_number), getResources().getString(R.string.str_quiz_wrong_number), getResources().getString(R.string.str_grade)}, false);

		tv_qstnNo = ww.getValueTextViews()[0];
		tv_wrongNo = ww.getValueTextViews()[1];
		tv_score = ww.getValueTextViews()[2];
	}

	private class finishTask extends AsyncTask<Context, Void, Integer> {
		@Override
		protected void onPreExecute() {
			progressDialog = new ProgressDialog(Test_Result.this);
			progressDialog.setMessage(getResources().getString(R.string.str_saving));
			progressDialog.setCancelable(false);
			progressDialog.show();
		}

		protected Integer doInBackground(Context... ctx) {
			if ( mQP.mPractice)
				return 0;

			for ( int i=0;i<mQP.mQstn_total;i++)
			{
				if ( mQP.mArr_ansPaper[i] > 0 && mQP.mArr_answer[i][mQP.mArr_ansPaper[i]-1])
				{
					dbHelper.updateStatQuestion(mQP.mArr_Qid[i], true);
					dbHelper.delQuestionInMissedList(mQP.mArr_Qid[i]);
				}
				else
				{
					dbHelper.updateStatQuestion(mQP.mArr_Qid[i], false);
					dbHelper.addQuestion2MissedList(mQP.mArr_Qid[i]);
				}
			}
			return 0;
		}

		@Override
		protected void onPostExecute(Integer err) {
			progressDialog.cancel();
			finish();
		}
	}

	private void showScore()
	{
		int no_cor = 0;

		for ( int i=0;i<mQP.mQstn_total;i++)
			if ( mQP.mArr_ansPaper[i] > 0 && mQP.mArr_answer[i][mQP.mArr_ansPaper[i]-1])
				no_cor++;

		mScore = (float) (((float)no_cor/(float)mQP.mQstn_total)*100.0);
		tv_qstnNo.setText(String.valueOf(mQP.mQstn_total));
		tv_wrongNo.setText(String.valueOf(mQP.mQstn_total - no_cor));
		tv_score.setText(String.format("%.1f", mScore));
	}

	private static final int ID_SAVE = 0;
	private static final int ID_NAME_LEN = 1;
	@Override
	protected Dialog onCreateDialog(int id) {
		AlertDialog.Builder builder = new AlertDialog.Builder(this);

		switch(id)
		{
		case ID_SAVE:
		{
			LayoutInflater inflater = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
			final EditText input = (EditText) inflater.inflate(R.layout.edittext_group_name, null);

			builder.setMessage(getResources().getString(R.string.str_create_group))
			.setView(input)
			.setPositiveButton(getResources().getString(R.string.str_save), new DialogInterface.OnClickListener() {
				@Override
				public void onClick(DialogInterface dialog, int which) {
					if (input.getText().length() < 1)
					{
						input.setText("");
						showDialog(ID_NAME_LEN);
					}
					else
					{
						long pid = dbHelper.addGroup(input.getText().toString());
						for ( int i=0;i<mQP.mQstn_total;i++)
						{
							dbHelper.addQuestion2Group(pid, mQP.mArr_Qid[i]);
						}
						b_prev.setVisibility(View.INVISIBLE);
					}
				}
			})
			.setNegativeButton(getResources().getString(R.string.str_cancel), null);
			break;
		}
		case ID_NAME_LEN:
		{
			builder.setMessage(getResources().getString(R.string.str_invalid_name))
			.setPositiveButton(getResources().getString(R.string.str_ok), null)
			.setCancelable(false);
			break;
		}
		default:
			break;
		}
		return builder.create();
	}

}
